#ifndef __SSU_AES_H__

#define __SSU_AES_H__
#include <openssl/aes.h>
#include <string.h>
#define ERROR 0

static unsigned char iv[16] = { 0x8, 0x1, 0x2, 0x1, 0x7A, 0x3, 0x7, 0x8, 0x5A,
		0x5B, 0x67, 0x36, 0x29, 0x71, 0x12, 0x32 };
static unsigned char iv1[16];
static unsigned char iv2[16];
/* AES Encryption function */

// Default Padding ISO 9797 M1
int ssu_encrypt(unsigned char* plainText, unsigned char* cipherText,
		unsigned char* binaryKey, int length) {
	AES_KEY key;
	unsigned char pad;
	unsigned char * plainBuf;

	if (AES_set_encrypt_key(binaryKey, 128, &key) < 0)
		return ERROR;
	memcpy(iv1, iv, 16);

	// #####PKCS5Padding
	pad = 16 - length % 16;
	plainBuf = (unsigned char *) calloc(length + pad, 1);
	memcpy(plainBuf, plainText, length);
	memset(plainBuf + length, pad, pad);
	AES_cbc_encrypt(plainBuf, cipherText, length + pad, &key, iv1, AES_ENCRYPT);
	free(plainBuf);
	return length + pad;
}

/* AES Decryption function */
int ssu_decrypt(unsigned char* cipherText, unsigned char* plainText,
		unsigned char* binaryKey, int length) {
	AES_KEY key;
	int i, ret = length;
	unsigned char pad = 0;

	if (AES_set_decrypt_key(binaryKey, 128, &key) < 0)
		return ERROR;
	memcpy(iv2, iv, 16);

	AES_cbc_encrypt(cipherText, plainText, length, &key, iv2, AES_DECRYPT);

	// #####PKCS5Padding
	pad = plainText[length - 1];
	memset(plainText + length - pad, 0, pad);
	ret = length - pad;
	return ret;
}

#endif // __SSU_AES_H__
